package com.dsmbase.corp.flow.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.dsmbase.corp.flow.domain.FlowBranch;

@Component
public class FlowBranchDao {

	private JdbcTemplate jdbcTemplate;
	
	private static final String SELECT_BY_ID_SQL = "select id, node_start, node_end, flow_id from flow_branch where id = ?";
	private static final String SELECT_BY_FLOWID_SQL = "select id, node_start, node_end, flow_id from flow_branch where flow_id = ?";
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public FlowBranch getFlowBranchById(int id) throws SQLException {
		Object[] params = new Object[] { id };
		FlowBranch flowBranch = null;
		try {
	    	flowBranch = (FlowBranch) jdbcTemplate.queryForObject(SELECT_BY_ID_SQL,
					params, new FlowBranchRowMapper());
		} catch (EmptyResultDataAccessException e) {
			throw new SQLException(e);
		}
		return flowBranch;
	}

	public List<FlowBranch> getFlowBranchByFlowId(int flowId) throws SQLException  {
		Object[] params = new Object[] { flowId };
		List<FlowBranch> flowBranchList = jdbcTemplate.query(SELECT_BY_FLOWID_SQL,
				params, new FlowBranchRowMapper());
		return flowBranchList;
	}
	
	public class FlowBranchRowMapper implements RowMapper<FlowBranch> {

		public FlowBranch mapRow(ResultSet rs, int index) throws SQLException {
			FlowBranch flowBranch = new FlowBranch(rs.getInt("id"), rs.getInt("flow_id"), rs.getInt("node_start"),
					rs.getInt("node_end"));
			return flowBranch;
		}

	}
	
}
